<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <link rel="icon" href="./public/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>同风起 - 后台管理系统</title>
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4299E1',
                        secondary: '#DD6B20',
                        dark: '#1A202C',
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .table-shadow {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            }
            .btn-primary {
                @apply bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 shadow-md hover:shadow-lg;
            }
            /* 确保选中的标签页在焦点状态下文字仍为白色 */
            #applications-tab.bg-primary:focus,
            #job-postings-tab.bg-primary:focus,
            #services-tab.bg-primary:focus {
                @apply text-white;
            }
            .btn-secondary {
                @apply bg-secondary hover:bg-secondary/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 shadow-md hover:shadow-lg;
            }
            .badge {
                @apply px-2 py-1 text-xs font-medium rounded-full;
            }
            .badge-primary {
                @apply bg-primary/10 text-primary;
            }
            .badge-secondary {
                @apply bg-secondary/10 text-secondary;
            }
            .badge-success {
                @apply bg-green-100 text-green-800;
            }
        }
        
        /* 设置页面基本高度 */
        html {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        
        body {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow-y: auto;
            -ms-overflow-style: none;
            scrollbar-width: none;
        }
        
        /* 彻底隐藏所有浏览器的滚动条 */
        body::-webkit-scrollbar {
            display: none !important;
            width: 0 !important;
            height: 0 !important;
        }
        
        /* 增强Firefox的滚动条隐藏效果 */
        body {
            scrollbar-width: none !important;
        }
        
        /* 增强IE和Edge的滚动条隐藏效果 */
        body {
            -ms-overflow-style: none !important;
        }
        
        /* 表格容器设置 */
        #applications-container,
        #job-postings-container {
            overflow-x: auto;
            -ms-overflow-style: none;
            scrollbar-width: none;
        }
        
        /* 隐藏表格容器的所有浏览器滚动条 */
        #applications-container::-webkit-scrollbar,
        #job-postings-container::-webkit-scrollbar,
        #services-container::-webkit-scrollbar {
            display: none !important;
            width: 0 !important;
            height: 0 !important;
        }
    </style>
</head>
<body class="bg-gray-50">
    <div class="container mx-auto px-4 py-8">
        <header class="mb-10 text-center">
            <h1 class="text-3xl md:text-4xl font-bold text-dark mb-4">同风起 - 管理系统</h1>
            <p class="text-gray-600 max-w-2xl mx-auto">职位申请管理与岗位发布</p>
        </header>
        
        <!-- 导航标签 -->
        <div class="mb-6">
            <div class="inline-flex rounded-md shadow-sm" role="group">
                <button type="button" id="applications-tab" class="px-6 py-2 text-sm font-medium text-white bg-primary rounded-lg focus:z-10 focus:ring-2 focus:ring-primary focus:text-white mr-2">
                    职位申请管理
                </button>
                <button type="button" id="job-postings-tab" class="px-6 py-2 text-sm font-medium text-gray-700 bg-white border-t border-b border-r hover:bg-gray-50 rounded-lg focus:z-10 focus:ring-2 focus:ring-primary focus:text-primary mr-2">
                    岗位发布管理
                </button>
                <button type="button" id="services-tab" class="px-6 py-2 text-sm font-medium text-gray-700 bg-white border-t border-b border-r hover:bg-gray-50 rounded-lg focus:z-10 focus:ring-2 focus:ring-primary focus:text-primary">
                    业务服务管理
                </button>
            </div>
        </div>
        
        <!-- 搜索区域已移至applications-panel内部 -->
        
        <!-- 职位申请管理面板 -->
        <div id="applications-panel" class="space-y-6">
            <div class="mb-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div class="relative">
                    <input type="text" id="search-input" placeholder="搜索申请人姓名、职位或邮箱..." 
                           class="w-full md:w-96 pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                    <i class="fa fa-search absolute left-3 top-3 text-gray-400"></i>
                </div>
                <div class="flex gap-3">
                    <button id="refresh-btn" class="btn-primary">
                        <i class="fa fa-refresh mr-2"></i>刷新数据
                    </button>
                    <button id="export-btn" class="btn-secondary">
                        <i class="fa fa-download mr-2"></i>导出数据
                    </button>
                </div>
            </div>
            
            <div id="loading" class="hidden text-center py-16 flex items-center justify-center">
                <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary mb-4"></div>
                <p class="text-gray-600">正在加载数据...</p>
            </div>
            
            <div id="error-message" class="hidden bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
                <p><i class="fa fa-exclamation-circle mr-2"></i><span id="error-text">加载数据失败，请稍后重试</span></p>
            </div>
            
            <div id="applications-container" class="overflow-x-auto bg-white rounded-lg shadow-lg table-shadow">
                <!-- 表格，表头始终显示 -->
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">申请人姓名</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">邮箱</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">电话</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">申请职位</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工作经验</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">申请时间</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">处理状态</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <!-- 表体容器，用于控制显示和隐藏 -->
                    <tbody id="applications-table-body" class="bg-white divide-y divide-gray-200">
                        <!-- 申请数据将通过 JavaScript 动态加载 -->
                    </tbody>
                </table>
                
                <!-- 空数据提示，默认隐藏 -->
                <div id="no-data" class="hidden p-12 text-center">
                    <i class="fa fa-inbox text-gray-300 text-5xl mb-4"></i>
                    <h3 class="text-xl font-medium text-gray-500 mb-2">暂无职位申请数据</h3>
                    <p class="text-gray-400">当有新的职位申请提交后，将在这里显示</p>
                </div>
            </div>
            
            <div id="pagination" class="mt-6 flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    显示 <span id="start-item">0</span> 到 <span id="end-item">0</span> 条，共 <span id="total-items">0</span> 条
                </div>
                <div class="flex items-center gap-2">
                    <button id="prev-page" class="px-3 py-1 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fa fa-chevron-left"></i>
                    </button>
                    <span id="page-info" class="text-sm text-gray-600">第 <span id="current-page">1</span> 页，共 <span id="total-pages">1</span> 页</span>
                    <button id="next-page" class="px-3 py-1 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fa fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 岗位发布管理面板 -->
        <div id="job-postings-panel" class="space-y-6 hidden">
            <div class="mb-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div class="relative">
                    <input type="text" id="job-search-input" placeholder="搜索岗位名称或类别..." 
                           class="w-full md:w-96 pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                    <i class="fa fa-search absolute left-3 top-3 text-gray-400"></i>
                </div>
                <div class="flex gap-3">
                    <button id="job-refresh-btn" class="btn-primary">
                        <i class="fa fa-refresh mr-2"></i>刷新数据
                    </button>
                    <button id="create-job-btn" class="btn-secondary">
                        <i class="fa fa-plus mr-2"></i>发布新岗位
                    </button>
                </div>
            </div>
            
            <div id="job-loading" class="hidden text-center py-20">
                <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary mb-4"></div>
                <p class="text-gray-600">正在加载数据...</p>
            </div>
            
            <div id="job-no-data" class="hidden bg-white rounded-lg p-12 text-center table-shadow">
                <i class="fa fa-briefcase text-gray-300 text-5xl mb-4"></i>
                <h3 class="text-xl font-medium text-gray-500 mb-2">暂无岗位数据</h3>
                <p class="text-gray-400">点击"发布新岗位"按钮创建您的第一个岗位</p>
            </div>
            
            <div id="job-error-message" class="hidden bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
                <p><i class="fa fa-exclamation-circle mr-2"></i><span id="job-error-text">加载数据失败，请稍后重试</span></p>
            </div>
            
            <div id="job-postings-container" class="overflow-x-auto bg-white rounded-lg shadow-lg table-shadow">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">岗位名称</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类别</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">地点</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">薪资</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody id="job-postings-table-body" class="bg-white divide-y divide-gray-200">
                        <!-- 岗位数据将通过 JavaScript 动态加载 -->
                    </tbody>
                </table>
            </div>
            
            <div id="job-pagination" class="mt-6 flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    显示 <span id="job-start-item">0</span> 到 <span id="job-end-item">0</span> 条，共 <span id="job-total-items">0</span> 条
                </div>
                <div class="flex items-center gap-2">
                    <button id="job-prev-page" class="px-3 py-1 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fa fa-chevron-left"></i>
                    </button>
                    <span id="job-page-info" class="text-sm text-gray-600">第 <span id="job-current-page">1</span> 页，共 <span id="job-total-pages">1</span> 页</span>
                    <button id="job-next-page" class="px-3 py-1 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fa fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 分页区域已移至各自面板内部 -->
        
        <!-- 业务服务管理面板 -->
        <div id="services-panel" class="space-y-6 hidden">
            <div class="mb-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div class="relative">
                    <input type="text" id="service-search-input" placeholder="搜索服务名称或类别..." 
                           class="w-full md:w-96 pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                    <i class="fa fa-search absolute left-3 top-3 text-gray-400"></i>
                </div>
                <div class="flex gap-3">
                    <button id="service-refresh-btn" class="btn-primary">
                        <i class="fa fa-refresh mr-2"></i>刷新数据
                    </button>
                    <button id="create-service-btn" class="btn-secondary">
                        <i class="fa fa-plus mr-2"></i>添加新服务
                    </button>
                </div>
            </div>
            
            <div id="service-loading" class="hidden text-center py-20">
                <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary mb-4"></div>
                <p class="text-gray-600">正在加载数据...</p>
            </div>
            
            <div id="service-no-data" class="hidden bg-white rounded-lg p-12 text-center table-shadow">
                <i class="fa fa-cogs text-gray-300 text-5xl mb-4"></i>
                <h3 class="text-xl font-medium text-gray-500 mb-2">暂无服务数据</h3>
                <p class="text-gray-400">点击"添加新服务"按钮创建您的第一个服务</p>
            </div>
            
            <div id="service-error-message" class="hidden bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
                <p><i class="fa fa-exclamation-circle mr-2"></i><span id="service-error-text">加载数据失败，请稍后重试</span></p>
            </div>
            
            <div id="services-container" class="overflow-x-auto bg-white rounded-lg shadow-lg table-shadow">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
        <tr>
            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">服务名称</th>
            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
            <th scope="col" class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
        </tr>
                    </thead>
                    <tbody id="services-table-body" class="bg-white divide-y divide-gray-200">
                        <!-- 服务数据将通过 JavaScript 动态加载 -->
                    </tbody>
                </table>
            </div>
            
            <div id="service-pagination" class="mt-6 flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    显示 <span id="service-start-item">0</span> 到 <span id="service-end-item">0</span> 条，共 <span id="service-total-items">0</span> 条
                </div>
                <div class="flex items-center gap-2">
                    <button id="service-prev-page" class="px-3 py-1 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fa fa-chevron-left"></i>
                    </button>
                    <span id="service-page-info" class="text-sm text-gray-600">第 <span id="service-current-page">1</span> 页，共 <span id="service-total-pages">1</span> 页</span>
                    <button id="service-next-page" class="px-3 py-1 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fa fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>

        <footer class="mt-12 text-center text-gray-500 text-sm">
            <p>© 2025 同风起信息科技有限公司 | 管理系统</p>
        </footer>
    </div>
    
    <!-- 详情模态框 -->
    <div id="details-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div class="bg-white rounded-lg max-w-3xl w-full max-h-[80vh] overflow-y-auto">
                <div class="p-6 border-b border-gray-200">
                    <div class="flex justify-between items-center">
                        <h3 class="text-xl font-bold text-gray-900">申请详情</h3>
                        <button id="close-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                            <i class="fa fa-times text-xl"></i>
                        </button>
                    </div>
                </div>
                <div id="modal-content" class="p-6">
                    <!-- 详情内容将通过 JavaScript 动态加载 -->
                </div>
                <div class="p-6 border-t border-gray-200 flex justify-end gap-3">
                    <button id="close-modal-btn" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">关闭</button>
                    <button id="delete-application-btn" class="px-4 py-2 bg-red-500 hover:bg-red-600 text-white font-medium rounded-lg transition-all duration-300 shadow-md hover:shadow-lg">
                        <i class="fa fa-trash mr-2"></i>删除申请
                    </button>
                    <button id="download-resume-btn" class="btn-primary hidden">
                        <i class="fa fa-download mr-2"></i>下载简历
                    </button>
                </div>
            </div>
        </div>
        
    <!-- 服务编辑模态框 -->
        <div id="service-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div class="bg-white rounded-lg max-w-xl w-full max-h-[90vh] overflow-y-auto">
                <div class="p-6 border-b border-gray-200">
                    <div class="flex justify-between items-center">
                        <h3 id="service-modal-title" class="text-xl font-bold text-gray-900">添加新服务</h3>
                        <button id="close-service-modal" class="text-gray-500 hover:text-gray-700 focus:outline-none p-2 rounded-full hover:bg-gray-100 transition-colors duration-200">
                            <i class="fa fa-times text-xl"></i>
                        </button>
                    </div>
                </div>
                <div class="p-6">
                    <form id="service-form">
                        <input type="hidden" id="service-id">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                            <div>
                                <label for="service-name" class="block text-sm font-medium text-gray-700 mb-1">服务名称 <span class="text-red-500">*</span></label>
                                <input type="text" id="service-name" name="service-name" required
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary">
                            </div>

                            <div>
                                <label for="service-icon" class="block text-sm font-medium text-gray-700 mb-1">服务图标</label>
                                <input type="text" id="service-icon" name="service-icon"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary">
                                <p class="mt-1 text-xs text-gray-500">使用 Font Awesome 图标名称（例如：fa-cogs）</p>
                            </div>
                            <div class="hidden">
                                <label for="service-icon-color" class="block text-sm font-medium text-gray-700 mb-1">图标颜色</label>
                                <input type="text" id="service-icon-color" name="service-icon-color"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" value="text-primary-600">
                                <p class="mt-1 text-xs text-gray-500">使用CSS颜色值（例如：#1890ff或primary）</p>
                            </div>
                            <div class="hidden">
                                <label for="service-icon-bg" class="block text-sm font-medium text-gray-700 mb-1">图标背景</label>
                                <input type="text" id="service-icon-bg" name="service-icon-bg"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary" value="bg-gradient-to-br from-primary-50 to-primary-100">
                                <p class="mt-1 text-xs text-gray-500">使用CSS颜色值（例如：#f0f9ff）</p>
                            </div>
                            <div>
                                <label for="service-status" class="block text-sm font-medium text-gray-700 mb-1">服务状态</label>
                                <select id="service-status" name="service-status" 
                                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary">
                                    <option value="active">激活</option>
                                    <option value="inactive">未激活</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-6">
                            <label for="service-description" class="block text-sm font-medium text-gray-700 mb-1">服务描述</label>
                            <textarea id="service-description" name="service-description" rows="5"
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary"></textarea>
                        </div>
                        
                        <div class="mb-6">
                            <label for="service-features" class="block text-sm font-medium text-gray-700 mb-1">服务特性</label>
                            <textarea id="service-features" name="service-features" rows="5"
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary"></textarea>
                            <p class="mt-1 text-xs text-gray-500">使用换行符分隔不同的特性</p>
                        </div>
                        
                        <div class="mb-6">
                            <label for="service-results" class="block text-sm font-medium text-gray-700 mb-1">服务成果</label>
                            <textarea id="service-results" name="service-results" rows="5"
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary"></textarea>
                        </div>
                    </form>
                </div>
                <div class="p-6 border-t border-gray-200 flex justify-end gap-3">
                    <button id="cancel-service-btn" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">取消</button>
                    <button id="save-service-btn" class="btn-primary">保存服务</button>
                </div>
            </div>
        </div>
        
        <!-- 岗位编辑模态框 -->
        <div id="job-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div class="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
                <div class="p-6 border-b border-gray-200">
                    <div class="flex justify-between items-center">
                        <h3 id="job-modal-title" class="text-xl font-bold text-gray-900">发布新岗位</h3>
                        <button id="close-job-modal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                            <i class="fa fa-times text-xl"></i>
                        </button>
                    </div>
                </div>
                <div class="p-6">
                    <form id="job-form">
                        <input type="hidden" id="job-id">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                            <div>
                                <label for="job-title" class="block text-sm font-medium text-gray-700 mb-1">岗位名称 <span class="text-red-500">*</span></label>
                                <input type="text" id="job-title" name="job-title" required
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary">
                            </div>
                            <div>
                                <label for="job-category" class="block text-sm font-medium text-gray-700 mb-1">岗位类别</label>
                                <input type="text" id="job-category" name="job-category"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary">
                            </div>
                            <div>
                                <label for="job-location" class="block text-sm font-medium text-gray-700 mb-1">工作地点</label>
                                <input type="text" id="job-location" name="job-location"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary">
                            </div>
                            <div>
                                <label for="job-salary" class="block text-sm font-medium text-gray-700 mb-1">薪资范围</label>
                                <input type="text" id="job-salary" name="job-salary"
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary">
                            </div>
                        </div>
                        
                        <div class="mb-6">
                            <label for="job-responsibilities" class="block text-sm font-medium text-gray-700 mb-1">岗位职责 <span class="text-red-500">*</span></label>
                            <textarea id="job-responsibilities" name="job-responsibilities" rows="5" required
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary"></textarea>
                            <p class="mt-1 text-xs text-gray-500">使用换行符分隔不同的职责（每条职责以数字开始）</p>
                        </div>
                        
                        <div class="mb-6">
                            <label for="job-requirements" class="block text-sm font-medium text-gray-700 mb-1">任职要求 <span class="text-red-500">*</span></label>
                            <textarea id="job-requirements" name="job-requirements" rows="5" required
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary"></textarea>
                            <p class="mt-1 text-xs text-gray-500">使用换行符分隔不同的要求（每条要求以数字开始）</p>
                        </div>
                        
                        <div class="mb-6">
                            <label for="job-highlights" class="block text-sm font-medium text-gray-700 mb-1">团队亮点</label>
                            <textarea id="job-highlights" name="job-highlights" rows="3"
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary"></textarea>
                            <p class="mt-1 text-xs text-gray-500">使用换行符分隔不同的亮点（每条亮点以数字开始）</p>
                        </div>
                        
                        <div class="mb-6">
                            <label for="job-tech-stack" class="block text-sm font-medium text-gray-700 mb-1">技术栈</label>
                            <textarea id="job-tech-stack" name="job-tech-stack" rows="2"
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary"></textarea>
                            <p class="mt-1 text-xs text-gray-500">使用逗号分隔不同的技术（例如：Vue.js, React, TypeScript）</p>
                        </div>
                        
                        <div class="mb-6">
                            <label class="flex items-center">
                                <input type="checkbox" id="job-is-active" name="job-is-active" checked
                                       class="h-4 w-4 text-primary border-gray-300 rounded focus:ring-primary">
                                <span class="ml-2 block text-sm text-gray-700">岗位有效（前端显示）</span>
                            </label>
                        </div>
                    </form>
                </div>
                <div class="p-6 border-t border-gray-200 flex justify-end gap-3">
                    <button id="cancel-job-btn" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">取消</button>
                    <button id="save-job-btn" class="btn-primary">保存岗位</button>
                </div>
            </div>
        </div>
    
    <script>
        // 全局变量
        let allApplications = [];
        let filteredApplications = [];
        let currentPage = 1;
        const itemsPerPage = 10;
        let currentApplicationId = null;
        
        // 全局变量
        let currentTab = 'applications';
        let allJobPostings = [];
        let filteredJobPostings = [];
        let currentJobId = null;
        let currentJobPage = 1;
        let jobItemsPerPage = 10;
        
        // DOM 加载完成后执行
        document.addEventListener('DOMContentLoaded', () => {
            // 设置默认标签
            currentTab = 'applications';
            
            // 初始化加载状态位置
            initLoadingPosition();
            
            // 加载默认标签数据 - 职位申请
            loadApplications();
            
            // 事件监听 - 标签页切换
            document.getElementById('applications-tab').addEventListener('click', () => switchTab('applications'));
            document.getElementById('job-postings-tab').addEventListener('click', () => switchTab('job-postings'));
            document.getElementById('services-tab').addEventListener('click', () => switchTab('services'));
            
            // 职位申请相关事件监听
            document.getElementById('refresh-btn').addEventListener('click', () => loadApplications(currentPage, true));
            document.getElementById('export-btn').addEventListener('click', exportToExcel);
            document.getElementById('search-input').addEventListener('input', handleSearch);
            document.getElementById('prev-page').addEventListener('click', goToPrevPage);
            document.getElementById('next-page').addEventListener('click', goToNextPage);
            document.getElementById('close-modal').addEventListener('click', closeModal);
            document.getElementById('close-modal-btn').addEventListener('click', closeModal);
            document.getElementById('download-resume-btn').addEventListener('click', downloadResume);
            document.getElementById('delete-application-btn').addEventListener('click', handleDeleteApplication);
            
            // 岗位管理相关事件监听
            document.getElementById('job-refresh-btn').addEventListener('click', () => loadJobPostings(currentJobPage, true));
            document.getElementById('create-job-btn').addEventListener('click', () => openJobModal());
            document.getElementById('job-search-input').addEventListener('input', handleJobSearch);
            
            // 绑定岗位分页按钮事件
            document.getElementById('job-prev-page').addEventListener('click', () => {
                if (currentJobPage > 1) {
                    currentJobPage--;
                    renderJobTable();
                }
            });
            
            document.getElementById('job-next-page').addEventListener('click', () => {
                const totalPages = Math.ceil(filteredJobPostings.length / jobItemsPerPage);
                if (currentJobPage < totalPages) {
                    currentJobPage++;
                    renderJobTable();
                }
            });
            document.getElementById('close-job-modal').addEventListener('click', closeJobModal);
            document.getElementById('cancel-job-btn').addEventListener('click', closeJobModal);
            document.getElementById('save-job-btn').addEventListener('click', saveJob);
            
            // 为处理状态按钮添加事件委托
            document.getElementById('applications-table-body').addEventListener('click', (e) => {
                if (e.target.closest('.processing-status')) {
                    const btn = e.target.closest('.processing-status');
                    const id = parseInt(btn.getAttribute('data-id'));
                    const currentStatus = btn.getAttribute('data-status') === 'true' || btn.getAttribute('data-status') === '1';
                    updateProcessingStatus(id, !currentStatus);
                }
            });
            
            // 为岗位表格添加事件委托
            document.getElementById('job-postings-table-body').addEventListener('click', (e) => {
                // 编辑按钮点击
                if (e.target.closest('.edit-job')) {
                    const btn = e.target.closest('.edit-job');
                    const id = parseInt(btn.getAttribute('data-id'));
                    editJob(id);
                }
                // 删除按钮点击
                else if (e.target.closest('.delete-job')) {
                    const btn = e.target.closest('.delete-job');
                    const id = parseInt(btn.getAttribute('data-id'));
                    const title = btn.getAttribute('data-title');
                    showConfirmDialog(
                        '确认删除',
                        `确定要删除岗位"${title}"吗？此操作不可恢复。`,
                        () => {
                            deleteJob(id);
                        }
                    );
                }
                // 状态切换按钮点击
                else if (e.target.closest('.job-status')) {
                    const btn = e.target.closest('.job-status');
                    const id = parseInt(btn.getAttribute('data-id'));
                    const currentStatus = btn.getAttribute('data-status') === 'true' || btn.getAttribute('data-status') === '1';
                    toggleJobStatus(id, !currentStatus);
                }
            });
        });
        
        // 切换标签页
        function switchTab(tab) {
            if (currentTab === tab) return;
            
            // 更新当前标签
            currentTab = tab;
            
            // 更新标签样式 - 重置所有标签样式
            document.getElementById('applications-tab').classList.remove('text-white', 'bg-primary');
            document.getElementById('applications-tab').classList.add('text-gray-700', 'bg-white', 'border-t', 'border-b', 'border-r', 'hover:bg-gray-50');
            document.getElementById('job-postings-tab').classList.remove('text-white', 'bg-primary');
            document.getElementById('job-postings-tab').classList.add('text-gray-700', 'bg-white', 'border-t', 'border-b', 'border-r', 'hover:bg-gray-50');
            document.getElementById('services-tab').classList.remove('text-white', 'bg-primary');
            document.getElementById('services-tab').classList.add('text-gray-700', 'bg-white', 'border-t', 'border-b', 'border-r', 'hover:bg-gray-50');
            
            // 隐藏所有面板
            document.getElementById('applications-panel').classList.add('hidden');
            document.getElementById('job-postings-panel').classList.add('hidden');
            document.getElementById('services-panel').classList.add('hidden');
            
            // 隐藏所有无数据提示
            document.getElementById('no-data').classList.add('hidden');
            document.getElementById('job-no-data').classList.add('hidden');
            document.getElementById('service-no-data').classList.add('hidden');
            
            // 根据选中的标签设置激活样式并显示对应面板
            if (tab === 'applications') {
                document.getElementById('applications-tab').classList.remove('text-gray-700', 'bg-white', 'border-t', 'border-b', 'border-r', 'hover:bg-gray-50');
                document.getElementById('applications-tab').classList.add('text-white', 'bg-primary');
                document.getElementById('applications-panel').classList.remove('hidden');
                loadApplications();
            } else if (tab === 'job-postings') {
                document.getElementById('job-postings-tab').classList.remove('text-gray-700', 'bg-white', 'border-t', 'border-b', 'border-r', 'hover:bg-gray-50');
                document.getElementById('job-postings-tab').classList.add('text-white', 'bg-primary');
                document.getElementById('job-postings-panel').classList.remove('hidden');
                loadJobPostings();
            } else if (tab === 'services') {
                document.getElementById('services-tab').classList.remove('text-gray-700', 'bg-white', 'border-t', 'border-b', 'border-r', 'hover:bg-gray-50');
                document.getElementById('services-tab').classList.add('text-white', 'bg-primary');
                document.getElementById('services-panel').classList.remove('hidden');
                loadServices();
            }
        }
        
        // 加载岗位数据
        async function loadJobPostings(page, forceRefresh = false) {
            // 确保所有容器都已初始化
            const jobContainer = document.getElementById('job-postings-container');
            const jobTableBody = document.getElementById('job-postings-table-body');
            const jobPagination = document.getElementById('job-pagination');
            
            // 移除隐藏状态，不设置固定高度，让容器根据内容自适应
            if (jobContainer) {
                jobContainer.classList.remove('hidden');
                jobContainer.style.height = 'auto';
            }
            
            // 显示加载状态，隐藏其他内容
            document.getElementById('job-loading').classList.remove('hidden');
            document.getElementById('job-no-data').classList.add('hidden');
            document.getElementById('job-error-message').classList.add('hidden');
            if (jobPagination) jobPagination.classList.add('hidden');
            
            // 清空表体内容，避免数据残留导致的布局问题
            if (jobTableBody) jobTableBody.innerHTML = '';
            
            try {
                // 设置请求超时
                const timeoutPromise = new Promise((_, reject) => {
                    setTimeout(() => reject(new Error('请求超时，请稍后重试')), 10000);
                });
                
                // 构建带分页参数的URL
                const url = new URL('/api/admin/job-postings', window.location.origin);
                url.searchParams.append('page', page || currentJobPage);
                url.searchParams.append('limit', jobItemsPerPage);
                
                // 调用后端 API 获取数据，添加超时处理
                const fetchPromise = fetch(url, { 
                    credentials: 'same-origin',
                    headers: {
                        'Accept': 'application/json'
                    }
                });
                
                const response = await Promise.race([fetchPromise, timeoutPromise]);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                
                // 处理新的API响应格式
                allJobPostings = result.data || [];
                filteredJobPostings = [...allJobPostings];
                
                // 更新分页信息
                totalJobRecords = result.pagination?.total || 0;
                totalJobPages = result.pagination?.totalPages || 1;
                jobItemsPerPage = result.pagination?.limit || 10;
                
                // 更新当前页码，只在没有提供页码时重置为第1页
                if (page) {
                    currentJobPage = page;
                } else {
                    currentJobPage = 1;
                }
                
                // 渲染表格数据
                renderJobTable();
                
                // 根据是否有数据显示相应内容
                if (allJobPostings.length === 0) {
                    document.getElementById('job-no-data').classList.remove('hidden');
                } else {
                    document.getElementById('job-postings-container').classList.remove('hidden');
                    document.getElementById('job-pagination').classList.remove('hidden');
                }
                
            } catch (error) {
                console.error('加载岗位数据失败:', error);
                document.getElementById('job-error-text').textContent = `加载数据失败: ${error.message}`;
                document.getElementById('job-error-message').classList.remove('hidden');
            } finally {
                // 隐藏加载状态
                document.getElementById('job-loading').classList.add('hidden');
            }
        }
        
        // 渲染岗位表格
        function renderJobTable() {
            const tableBody = document.getElementById('job-postings-table-body');
            tableBody.innerHTML = '';
            
            // 使用从API获取的分页信息
            const totalItems = totalJobRecords || 0;
            const totalPages = totalJobPages || 1;
            const startItem = (currentJobPage - 1) * jobItemsPerPage + 1;
            const endItem = Math.min(startItem + jobItemsPerPage - 1, totalItems);
            
            // 由于API已经返回了分页数据，直接使用filteredJobPostings
            const paginatedData = filteredJobPostings;
            
            // 更新分页信息
            document.getElementById('job-start-item').textContent = totalItems > 0 ? startItem : 0;
            document.getElementById('job-end-item').textContent = totalItems > 0 ? endItem : 0;
            document.getElementById('job-total-items').textContent = totalItems;
            document.getElementById('job-current-page').textContent = currentJobPage;
            document.getElementById('job-total-pages').textContent = totalPages;
            
            // 更新分页按钮状态
            document.getElementById('job-prev-page').disabled = currentJobPage === 1;
            document.getElementById('job-next-page').disabled = currentJobPage === totalPages;
            
            // 渲染数据
            paginatedData.forEach(job => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${job.id}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${job.title || '未知'}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="badge badge-secondary">${job.category || '未分类'}</span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${job.location || '未指定'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${job.salary || '未公开'}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <button class="job-status px-3 py-1 rounded-full text-sm ${job.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}" data-id="${job.id}" data-status="${job.is_active}">
                            ${job.is_active ? '有效' : '已下架'}
                        </button>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatDate(job.created_at)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button class="text-primary hover:text-primary/80 mr-3 edit-job p-1.5 rounded-lg hover:bg-primary/10 transition-colors" data-id="${job.id}" title="编辑岗位">
                            <i class="fa fa-pencil"></i>
                        </button>
                        <button class="text-red-500 hover:text-red-600 delete-job p-1.5 rounded-lg hover:bg-red-100 transition-colors" data-id="${job.id}" data-title="${job.title}" title="删除岗位">
                            <i class="fa fa-trash"></i>
                        </button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }
        
        // 处理岗位搜索
        function handleJobSearch(event) {
            const searchTerm = event.target.value.toLowerCase();
            
            // 重置当前页
            currentJobPage = 1;
            
            // 根据搜索词过滤岗位
            filteredJobPostings = allJobPostings.filter(job => {
                const title = (job.title || '').toLowerCase();
                const category = (job.category || '').toLowerCase();
                
                return title.includes(searchTerm) || category.includes(searchTerm);
            });
            
            // 重新渲染表格
            renderJobTable();
            
            // 显示或隐藏空状态
            const noDataElement = document.getElementById('job-no-data');
            if (filteredJobPostings.length === 0 && allJobPostings.length > 0) {
                noDataElement.innerHTML = `
                    <i class="fa fa-search text-gray-300 text-5xl mb-4"></i>
                    <h3 class="text-xl font-medium text-gray-500 mb-2">未找到匹配的岗位</h3>
                    <p class="text-gray-400">请尝试使用不同的搜索词</p>
                `;
                noDataElement.classList.remove('hidden');
            } else if (filteredJobPostings.length === 0 && allJobPostings.length === 0) {
                noDataElement.innerHTML = `
                    <i class="fa fa-briefcase text-gray-300 text-5xl mb-4"></i>
                    <h3 class="text-xl font-medium text-gray-500 mb-2">暂无岗位数据</h3>
                    <p class="text-gray-400">点击"发布新岗位"按钮创建您的第一个岗位</p>
                `;
                noDataElement.classList.remove('hidden');
            } else {
                noDataElement.classList.add('hidden');
            }
        }
        
        // 打开岗位编辑模态框
        function openJobModal() {
            // 重置表单
            document.getElementById('job-form').reset();
            document.getElementById('job-id').value = '';
            document.getElementById('job-modal-title').textContent = '发布新岗位';
            currentJobId = null;
            
            // 显示模态框
            document.getElementById('job-modal').classList.remove('hidden');
        }
        
        // 编辑岗位
        function editJob(id) {
            const job = allJobPostings.find(job => job.id === id);
            if (!job) return;
            
            // 填充表单数据
            document.getElementById('job-id').value = job.id;
            document.getElementById('job-title').value = job.title || '';
            document.getElementById('job-category').value = job.category || '';
            document.getElementById('job-location').value = job.location || '';
            document.getElementById('job-salary').value = job.salary || '';
            document.getElementById('job-responsibilities').value = job.responsibilities || '';
            document.getElementById('job-requirements').value = job.requirements || '';
            document.getElementById('job-highlights').value = job.highlights || '';
            document.getElementById('job-tech-stack').value = job.tech_stack || '';
            document.getElementById('job-is-active').checked = job.is_active === 1 || job.is_active === true;
            
            // 更新标题和当前ID
            document.getElementById('job-modal-title').textContent = '编辑岗位';
            currentJobId = id;
            
            // 显示模态框
            document.getElementById('job-modal').classList.remove('hidden');
        }
        
        // 关闭岗位模态框
        function closeJobModal() {
            document.getElementById('job-modal').classList.add('hidden');
            currentJobId = null;
        }
        
        // 保存岗位
        async function saveJob() {
            // 获取表单数据
            const title = document.getElementById('job-title').value.trim();
            const category = document.getElementById('job-category').value.trim();
            const location = document.getElementById('job-location').value.trim();
            const salary = document.getElementById('job-salary').value.trim();
            const responsibilities = document.getElementById('job-responsibilities').value.trim();
            const requirements = document.getElementById('job-requirements').value.trim();
            const highlights = document.getElementById('job-highlights').value.trim();
            const tech_stack = document.getElementById('job-tech-stack').value.trim();
            const is_active = document.getElementById('job-is-active').checked;
            
            // 记录表单数据
            console.log('表单数据准备提交:', { title, category, location, salary, responsibilities, requirements, highlights, tech_stack, is_active });
            
            // 验证必填字段
            if (!title || !responsibilities || !requirements) {
                showToast('请填写所有必填字段（带*的字段）', 'error');
                return;
            }
            
            try {
                let response;
                
                console.log('执行操作类型:', currentJobId ? '更新岗位' : '新增岗位');
                
                if (currentJobId) {
                    // 更新现有岗位
                    response = await fetch(`/api/job-postings/${currentJobId}`, {
                        credentials: 'include', // 修改为include确保凭证总是被发送
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            title,
                            category,
                            location,
                            salary,
                            responsibilities,
                            requirements,
                            highlights,
                            tech_stack,
                            is_active
                        })
                    });
                    console.log('[DEBUG] 发送更新岗位请求:', { id: currentJobId, title });
                } else {
                    // 创建新岗位
                    response = await fetch('/api/job-postings', { 
                        credentials: 'include', // 修改为include确保凭证总是被发送
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            title,
                            category,
                            location,
                            salary,
                            responsibilities,
                            requirements,
                            highlights,
                            tech_stack,
                            is_active
                        })
                    });
                    console.log('[DEBUG] 发送新增岗位请求:', { title, hasResponsibilities: !!responsibilities, hasRequirements: !!requirements });
                }
                
                // 记录响应状态
                console.log('API响应状态码:', response.status);
                
                // 检查状态码范围200-299表示成功
                if (response.status >= 200 && response.status < 300) {
                    // 获取并记录响应数据
                    const responseData = await response.json();
                    console.log('API调用成功，响应数据:', responseData);
                    // 显示成功消息 - 明确区分新增和更新操作
                    showToast(currentJobId ? '岗位更新成功' : '新增岗位成功', 'success');
                    
                    // 关闭模态框并刷新数据
                    closeJobModal();
                    loadJobPostings();
                } else {
                    // 尝试获取错误详情
                    let errorMessage = '保存失败';
                    try {
                        const errorData = await response.json();
                        console.log('API错误响应数据:', errorData);
                        errorMessage = errorData.error || errorData.message || errorMessage;
                    } catch (parseError) {
                        console.error('无法解析错误响应:', parseError);
                        // 如果无法解析JSON，保留默认错误消息
                    }
                    throw new Error(errorMessage);
                }
                
            } catch (error) {
                console.error('保存岗位失败详情:', error);
                // 更友好的错误提示，区分新增和更新场景
                const operationType = currentJobId ? '更新' : '新增';
                showToast(`${operationType}岗位失败: ${error.message || '请稍后重试'}`, 'error');
            }
        }
        
        // 删除岗位
        async function deleteJob(id) {
            try {
                const response = await fetch(`/api/job-postings/${id}`, {
                    method: 'DELETE',
                    credentials: 'same-origin', // 确保携带凭证
                    headers: {
                        'Accept': 'application/json' // 指定接收JSON格式响应
                    }
                });
                
                // 检查状态码范围200-299表示成功
                if (response.status >= 200 && response.status < 300) {
                    // 尝试解析响应内容，但即使解析失败也继续执行后续逻辑
                    try {
                        // 无论是否能成功解析响应，都刷新数据
                        // 这解决了删除成功但响应格式可能有问题的情况
                        const data = await response.json();
                        console.log('删除岗位响应:', data);
                    } catch (jsonError) {
                        console.warn('删除岗位成功，但无法解析响应内容:', jsonError);
                        // 不抛出错误，继续执行后续操作
                    }
                    
                    // 重要：强制刷新数据，确保UI与后端同步
                    // 特别是考虑到后端会重新编排ID，必须重新加载完整数据
                    await loadJobPostings();
                    
                    // 显示成功消息
                    showToast('岗位删除成功', 'success');
                } else {
                    // 处理错误状态码
                    try {
                        const errorData = await response.json();
                        throw new Error(errorData.error || '删除失败');
                    } catch (e) {
                        // 如果无法解析错误响应，使用默认错误
                        throw new Error('删除失败');
                    }
                }
                
            } catch (error) {
                console.error('删除岗位失败:', error);
                
                // 即使出现错误，也尝试刷新数据
                // 这解决了后端实际已删除但前端显示错误的情况
                try {
                    await loadJobPostings();
                    console.log('即使报错也刷新了数据，确保UI与后端同步');
                    // 修改：如果刷新数据后，可能已经成功删除，显示成功消息
                    showToast('岗位删除操作已处理，请检查列表确认', 'info');
                } catch (refreshError) {
                    // 如果刷新也失败，才显示错误消息
                    showToast(`删除失败: ${error.message || '未知错误'}`, 'error');
                }
            }
        }
        
        // 切换岗位状态
        async function toggleJobStatus(id, isActive) {
            try {
                // 先查找要更新的岗位数据，确保保留其他字段不变
                const job = allJobPostings.find(job => job.id === id);
                if (!job) {
                    console.error('岗位不存在');
                    showToast('岗位不存在', 'error');
                    return;
                }
                
                // 切换状态时只发送is_active字段，避免覆盖未保存的表单修改
                const updateData = {
                    is_active: isActive
                };
                
                console.log('更新岗位数据:', updateData);
                
                // 使用相对路径而不是绝对路径
                const response = await fetch(`/api/job-postings/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(updateData),
                    credentials: 'same-origin' // 确保携带凭证
                });
                
                console.log('API响应状态:', response.status);
                
                // 检查状态码范围200-299表示成功
                if (response.status >= 200 && response.status < 300) {
                    // 刷新数据
                    loadJobPostings();
                    
                    // 显示成功消息
                    const message = isActive ? '岗位已激活' : '岗位已下架';
                    console.log('显示成功消息:', message);
                    showToast(message, 'success');
                } else {
                    const errorText = await response.text();
                    console.error('更新失败:', errorText);
                    throw new Error('更新失败: ' + errorText);
                }
                
            } catch (error) {
                console.error('更新岗位状态失败:', error);
                showToast(`更新失败: ${error.message || '未知错误'}`, 'error');
            }
        }
        
        // 初始化加载状态位置
        function initLoadingPosition() {
            const loadingElement = document.getElementById('loading');
            const tableContainer = document.getElementById('applications-container');
            
            if (loadingElement && tableContainer && loadingElement.parentNode !== tableContainer) {
                // 将加载元素移到表格容器内部
                loadingElement.parentNode.removeChild(loadingElement);
                tableContainer.appendChild(loadingElement);
            }
        }
        
        // 添加数据缓存变量
        // 缓存相关变量
        let pageCache = {}; // 改为按页码缓存数据
        let cacheTimestamp = null;
        const CACHE_DURATION = 30000; // 缓存30秒
        const PAGE_SIZE = 10;
        
        // 分页相关变量
        let totalRecords = 0;
        let totalPages = 0;
        
        // 加载职位申请数据 - 支持分页优化
        async function loadApplications(page = 1, forceRefresh = false) {
            // 确保所有容器都已初始化
            const tableContainer = document.getElementById('applications-container');
            const tableBody = document.getElementById('applications-table-body');
            const paginationContainer = document.getElementById('pagination');
            const loadingElement = document.getElementById('loading');
            
            // 更新当前页码
            currentPage = page;
            
            // 移除隐藏状态，不设置固定高度，让容器根据内容自适应
            if (tableContainer) {
                tableContainer.classList.remove('hidden');
                tableContainer.style.height = 'auto';
            }
            
            // 确保加载状态在正确的位置
            initLoadingPosition();
            
            // 显示加载状态，隐藏其他内容
            loadingElement.classList.remove('hidden');
            document.getElementById('no-data').classList.add('hidden');
            document.getElementById('error-message').classList.add('hidden');
            if (paginationContainer) paginationContainer.classList.add('hidden');
            
            // 清空表体内容，避免数据残留导致的布局问题
            if (tableBody) tableBody.innerHTML = '';
            
            try {
                // 检查是否有有效的缓存数据
                const now = Date.now();
                const cacheKey = `page_${page}`;
                const isCacheValid = !forceRefresh && pageCache[cacheKey] && 
                                    cacheTimestamp && 
                                    (now - cacheTimestamp < CACHE_DURATION);
                
                if (isCacheValid) {
                    // 使用缓存数据
                    const cachedData = pageCache[cacheKey];
                    allApplications = cachedData.applications;
                    filteredApplications = [...allApplications];
                    totalRecords = cachedData.totalRecords;
                    totalPages = cachedData.totalPages;
                    console.log(`使用第${page}页缓存数据`);
                } else {
                    // 设置请求超时
                    const timeoutPromise = new Promise((_, reject) => {
                        setTimeout(() => reject(new Error('请求超时，请稍后重试')), 10000);
                    });
                    
                    // 构建带分页参数的API请求URL
                    const apiUrl = `/api/job-applications?page=${page}&limit=${PAGE_SIZE}`;
                    console.log(`加载分页数据: ${apiUrl}`);
                    
                    // 调用后端 API 获取分页数据，添加超时处理
                    const fetchPromise = fetch(apiUrl, { 
                        credentials: 'same-origin',
                        headers: {
                            'Accept': 'application/json'
                        }
                    });
                    
                    const response = await Promise.race([fetchPromise, timeoutPromise]);
                    
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    
                    // 解析响应数据
                    const result = await response.json();
                    
                    // 从新的API响应格式中提取数据
                    allApplications = result.data || [];
                    filteredApplications = [...allApplications];
                    totalRecords = result.pagination?.total || 0;
                    totalPages = result.pagination?.totalPages || 0;
                    
                    // 更新缓存
                    pageCache[cacheKey] = {
                        applications: allApplications,
                        totalRecords: totalRecords,
                        totalPages: totalPages
                    };
                    cacheTimestamp = now;
                }
                
                // 根据是否有数据显示相应内容
                if (allApplications.length === 0) {
                    // 清空表体内容
                    if (tableBody) tableBody.innerHTML = '';
                    // 显示空数据提示
                    document.getElementById('no-data').classList.remove('hidden');
                    // 隐藏分页
                    if (paginationContainer) paginationContainer.classList.add('hidden');
                } else {
                    // 渲染表格数据
                    renderTable();
                    // 隐藏空数据提示
                    document.getElementById('no-data').classList.add('hidden');
                    // 显示并更新分页控件
                    if (paginationContainer) {
                        paginationContainer.classList.remove('hidden');
                        updatePaginationUI();
                    }
                }
                
            } catch (error) {
                console.error('加载职位申请失败:', error);
                document.getElementById('error-text').textContent = `加载数据失败: ${error.message}`;
                document.getElementById('error-message').classList.remove('hidden');
            } finally {
                // 隐藏加载状态
                loadingElement.classList.add('hidden');
            }
        }
        
        // 更新分页UI
        function updatePaginationUI() {
            const paginationContainer = document.getElementById('pagination');
            if (!paginationContainer) return;
            
            // 清空现有的分页控件
            paginationContainer.innerHTML = '';
            
            // 创建与岗位发布管理相同的分页结构
            const startItem = totalRecords > 0 ? ((currentPage - 1) * PAGE_SIZE + 1) : 0;
            const endItem = Math.min(startItem + PAGE_SIZE - 1, totalRecords);
            
            // 更新分页信息元素
            paginationContainer.innerHTML = `
                <div class="text-sm text-gray-600">
                    显示 <span id="start-item">${startItem}</span> 到 <span id="end-item">${endItem}</span> 条，共 <span id="total-items">${totalRecords}</span> 条
                </div>
                <div class="flex items-center gap-2">
                    <button id="prev-page" class="px-3 py-1 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fa fa-chevron-left"></i>
                    </button>
                    <span class="text-sm text-gray-600">第 <span id="current-page">${currentPage}</span> 页，共 <span id="total-pages">${totalPages}</span> 页</span>
                    <button id="next-page" class="px-3 py-1 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fa fa-chevron-right"></i>
                    </button>
                </div>
            `;
            
            // 添加事件监听器
            document.getElementById('prev-page').addEventListener('click', () => {
                if (currentPage > 1) {
                    loadApplications(currentPage - 1);
                }
            });
            
            document.getElementById('next-page').addEventListener('click', () => {
                if (currentPage < totalPages) {
                    loadApplications(currentPage + 1);
                }
            });
        }
        
        // 渲染表格数据
        function renderTable() {
            const tableBody = document.getElementById('applications-table-body');
            if (!tableBody) {
                console.error('表格体元素不存在');
                return;
            }
            tableBody.innerHTML = '';
            
            // 直接使用后端返回的分页数据，不再在前端计算分页
            const paginatedApplications = filteredApplications || [];
            
            // 渲染每页数据
            paginatedApplications.forEach(application => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${application.id}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${application.name || '未知'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${application.email || '未知'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${application.phone || '未提供'}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="badge badge-primary">${application.position_name || '未指定'}</span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${application.work_experience || '未提供'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatDate(application.created_at)}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <button class="processing-status px-3 py-1 rounded-full text-sm ${application.is_processed ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'}" data-id="${application.id}" data-status="${application.is_processed}">
                            ${application.is_processed ? '已处理' : '未处理'}
                        </button>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button class="text-primary hover:text-primary/80 mr-3 view-details p-1.5 rounded-lg hover:bg-primary/10 transition-colors" data-id="${application.id}" title="查看详情">
                            <i class="fa fa-eye"></i>
                        </button>
                        ${application.serverFileName ? `
                        <button class="text-secondary hover:text-secondary/80 download-resume p-1.5 rounded-lg hover:bg-secondary/10 transition-colors" data-id="${application.id}" data-filename="${application.serverFileName}" title="下载简历">
                            <i class="fa fa-download"></i>
                        </button>` : '<span class="text-gray-400">无简历</span>'}
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 添加查看详情事件监听
            document.querySelectorAll('.view-details').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = parseInt(e.currentTarget.getAttribute('data-id'));
                    showApplicationDetails(id);
                });
            });
            
            // 添加直接下载简历事件监听
            document.querySelectorAll('.download-resume').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const filename = e.currentTarget.getAttribute('data-filename');
                    const id = e.currentTarget.getAttribute('data-id');
                    downloadResumeFile(filename, id);
                });
            });
        }
        
        // 显示申请详情
        function showApplicationDetails(id) {
            const application = filteredApplications.find(app => app.id === id);
            if (!application) return;
            
            currentApplicationId = id;
            const modalContent = document.getElementById('modal-content');
            
            modalContent.innerHTML = `
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                    <div>
                        <h4 class="text-sm font-medium text-gray-500 mb-1">申请人姓名</h4>
                        <p class="text-lg font-medium">${application.name || '未知'}</p>
                    </div>
                    <div>
                        <h4 class="text-sm font-medium text-gray-500 mb-1">申请职位</h4>
                        <p class="text-lg font-medium">${application.position_name || '未指定'}</p>
                    </div>
                    <div>
                        <h4 class="text-sm font-medium text-gray-500 mb-1">电子邮箱</h4>
                        <p>${application.email || '未知'}</p>
                    </div>
                    <div>
                        <h4 class="text-sm font-medium text-gray-500 mb-1">联系电话</h4>
                        <p>${application.phone || '未提供'}</p>
                    </div>
                    <div>
                        <h4 class="text-sm font-medium text-gray-500 mb-1">工作经验</h4>
                        <p>${application.work_experience || '未提供'}</p>
                    </div>
                    <div>
                        <h4 class="text-sm font-medium text-gray-500 mb-1">申请时间</h4>
                        <p>${formatDateTime(application.created_at)}</p>
                    </div>
                </div>
                
                ${application.serverFileName ? `
                <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                    <div class="flex items-center">
                        <i class="fa fa-file-pdf-o text-red-500 text-3xl mr-4"></i>
                        <div>
                            <h4 class="text-sm font-medium text-gray-500 mb-1">简历文件</h4>
                            <p class="text-sm text-gray-600 break-all">${application.serverFileName}</p>
                        </div>
                    </div>
                </div>
                ` : ''}
                
                ${application.message ? `
                <div>
                    <h4 class="text-sm font-medium text-gray-500 mb-2">个人简介</h4>
                    <div class="p-4 bg-gray-50 rounded-lg whitespace-pre-wrap">${application.message}</div>
                </div>
                ` : ''}
            `;
            
            // 显示模态框
            document.getElementById('details-modal').classList.remove('hidden');
            
            // 更新下载按钮状态
            const downloadBtn = document.getElementById('download-resume-btn');
            if (application.serverFileName) {
                downloadBtn.classList.remove('hidden');
                downloadBtn.setAttribute('data-filename', application.serverFileName);
            } else {
                downloadBtn.classList.add('hidden');
            }
            
            // 更新删除按钮状态
            const deleteBtn = document.getElementById('delete-application-btn');
            deleteBtn.setAttribute('data-id', application.id);
        }
        
        // 关闭模态框
        function closeModal() {
            document.getElementById('details-modal').classList.add('hidden');
            currentApplicationId = null;
        }
        
        // 下载简历
        function downloadResume() {
            const application = filteredApplications.find(app => app.id === currentApplicationId);
            if (application && application.serverFileName) {
                downloadResumeFile(application.serverFileName, application.id);
            }
        }
        
        // 显示下载进度模态窗口
        function showDownloadProgressModal(filename) {
            // 创建等待滚动模态窗口元素
            const modal = document.createElement('div');
            modal.id = 'download-progress-modal';
            modal.className = 'custom-modal-overlay';
            modal.innerHTML = `
                <div class="custom-modal download-progress-modal">
                    <div class="custom-modal-header">
                        <h3 class="custom-modal-title">正在下载简历</h3>
                    </div>
                    <div class="custom-modal-body">
                        <p class="file-name">文件名: ${filename}</p>
                        <div class="loading-container">
                            <div class="loading-bar">
                                <div class="loading-indicator"></div>
                            </div>
                            <div class="loading-info">
                                <span class="loading-status">正在处理请求...</span>
                            </div>
                        </div>
                        <div class="download-details">
                            <p class="download-tip">请等待下载完成，不要关闭此窗口</p>
                        </div>
                    </div>
                </div>
            `;
            
            // 添加到文档
            document.body.appendChild(modal);
            
            // 添加样式（如果还没有）
            if (!document.getElementById('download-progress-styles')) {
                const style = document.createElement('style');
                style.id = 'download-progress-styles';
                style.textContent = `
                    /* 确保模态窗口样式优先级高 */
                    .custom-modal-overlay {
                        position: fixed !important;
                        top: 0 !important;
                        left: 0 !important;
                        right: 0 !important;
                        bottom: 0 !important;
                        background-color: rgba(0, 0, 0, 0.6) !important;
                        display: flex !important;
                        align-items: center !important;
                        justify-content: center !important;
                        z-index: 9999 !important; /* 最高层级确保可见 */
                        animation: fadeIn 0.3s ease-out !important;
                    }
                    
                    /* 关键帧动画 */
                    @keyframes fadeIn {
                        from { opacity: 0; }
                        to { opacity: 1; }
                    }
                    
                    .custom-modal.download-progress-modal {
                        width: 450px !important;
                        max-width: 95% !important;
                        background-color: white !important;
                        border-radius: 12px !important;
                        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2) !important;
                        overflow: hidden !important;
                        animation: slideIn 0.3s ease-out !important;
                    }
                    
                    @keyframes slideIn {
                        from { transform: translateY(-30px); opacity: 0; }
                        to { transform: translateY(0); opacity: 1; }
                    }
                    
                    .custom-modal-header {
                        padding: 20px 24px !important;
                        background-color: #f8f9fa !important;
                        border-bottom: 1px solid #e9ecef !important;
                    }
                    
                    .custom-modal-title {
                        margin: 0 !important;
                        font-size: 18px !important;
                        font-weight: 600 !important;
                        color: #333 !important;
                        text-align: center !important;
                    }
                    
                    .custom-modal-body {
                        padding: 24px !important;
                    }
                    
                    .file-name {
                        font-size: 16px !important;
                        font-weight: 500 !important;
                        color: #495057 !important;
                        margin-bottom: 20px !important;
                        word-break: break-all !important;
                        text-align: center !important;
                    }
                    
                    .loading-container {
                        margin-bottom: 20px !important;
                    }
                    
                    .loading-bar {
                        width: 100% !important;
                        height: 24px !important;
                        background-color: #e9ecef !important;
                        border-radius: 12px !important;
                        overflow: hidden !important;
                        position: relative !important;
                        box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1) !important;
                        margin-bottom: 8px !important;
                    }
                    
                    .loading-indicator {
                        height: 100% !important;
                        width: 40% !important;
                        background-color: #4CAF50 !important;
                        background-image: linear-gradient(90deg, #4CAF50, #45a049) !important;
                        border-radius: 12px !important;
                        animation: scrollLoading 1.5s infinite ease-in-out !important;
                    }
                    
                    @keyframes scrollLoading {
                        0% {
                            transform: translateX(-100%);
                        }
                        100% {
                            transform: translateX(250%);
                        }
                    }
                    
                    .loading-info {
                        text-align: center !important;
                        font-size: 14px !important;
                    }
                    
                    .loading-status {
                        color: #4CAF50 !important;
                        font-weight: 500 !important;
                    }
                    
                    .download-details {
                        margin-top: 16px !important;
                        border-top: 1px solid #e9ecef !important;
                        padding-top: 16px !important;
                    }
                    
                    .download-tip {
                        font-size: 13px !important;
                        color: #868e96 !important;
                        margin: 0 !important;
                        font-style: italic !important;
                        text-align: center !important;
                    }
                `;
                document.head.appendChild(style);
            }
            
            // 返回更新状态的函数和关闭模态窗口的函数
            return {
                updateProgress: (progress, status) => {
                    const statusEl = modal.querySelector('.loading-status');
                    
                    if (statusEl && status) {
                        statusEl.textContent = status;
                    }
                },
                close: () => {
                    // 添加淡出动画
                    if (document.body.contains(modal)) {
                        modal.style.opacity = '0';
                        modal.style.transition = 'opacity 0.3s ease-out';
                        setTimeout(() => {
                            if (document.body.contains(modal)) {
                                document.body.removeChild(modal);
                            }
                        }, 300);
                    }
                }
            };
        }

        // 下载简历文件（带进度显示）
        async function downloadResumeFile(filename, applicationId) {
            // 优先使用ID模式下载，这样更可靠
            const downloadUrl = `/api/download-resume/${applicationId || encodeURIComponent(filename)}`;
            
            // 显示下载进度模态窗口
            const progressModal = showDownloadProgressModal(filename);
            
            // 立即显示等待状态，确保用户看到反馈
            progressModal.updateProgress(0, '正在处理请求...');
            console.log(`开始下载简历文件: ${filename}`);
            
            try {
                // 使用fetch API请求文件
                const response = await fetch(downloadUrl, {
                    method: 'GET',
                    headers: {
                        'Accept': '*/*'
                    }
                });
                
                if (!response.ok) {
                    let errorMessage = `下载失败: ${response.status}`;
                    
                    // 尝试获取服务器返回的具体错误信息
                    try {
                        const errorData = await response.json();
                        if (errorData && errorData.error) {
                            errorMessage = errorData.error;
                        }
                    } catch (parseError) {
                        // JSON解析失败，使用默认错误信息
                        console.log('无法解析错误响应:', parseError);
                    }
                    
                    // 关闭进度窗口，显示自定义的错误弹窗
                    progressModal.close();
                    
                    // 根据不同的错误类型显示不同的消息
                    if (response.status === 404) {
                        showCustomModal('简历文件不存在', 
                            errorMessage === '简历文件记录存在但文件内容丢失' ? 
                            '系统中存在该简历的记录，但文件内容可能已损坏或丢失。' : 
                            '该简历文件可能已被删除或移动。');
                        throw new Error(errorMessage);
                    } else if (response.status === 400) {
                        showCustomModal('无效的请求', errorMessage);
                    } else {
                        showCustomModal('下载失败', `无法下载简历文件: ${errorMessage}`);
                    }
                    throw new Error(errorMessage);
                }
                
                // 获取内容长度
                const contentLength = response.headers.get('content-length');
                const totalSize = contentLength ? parseInt(contentLength, 10) : 0;
                
                console.log(`下载文件: ${filename}, 总大小: ${formatFileSize(totalSize)}`);
                
                // 改进的兼容性处理
                if (!response.body || !ReadableStream || typeof response.body.getReader !== 'function') {
                    console.log('浏览器不支持ReadableStream API，使用兼容性模式');
                    // 模拟进度更新，确保用户看到反馈
                    progressModal.updateProgress(10, '获取文件信息...');
                    
                    // 模拟一些进度更新，提供更好的用户体验
                    const progressInterval = setInterval(() => {
                        const currentProgress = parseInt(document.getElementById('progress-fill').style.width);
                        if (currentProgress < 70) {
                            progressModal.updateProgress(Math.min(currentProgress + 5, 70), '下载中...');
                        }
                    }, 200);
                    
                    const blob = await response.blob();
                    clearInterval(progressInterval);
                    
                    progressModal.updateProgress(100, '准备保存文件...');
                    
                    // 创建下载链接
                    const link = document.createElement('a');
                    const url = window.URL.createObjectURL(blob);
                    link.href = url;
                    link.download = filename;
                    document.body.appendChild(link);
                    link.click();
                    
                    // 清理
                    setTimeout(() => {
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(url);
                        progressModal.close();
                    }, 1000);
                    
                    console.log(`文件下载完成，大小: ${formatFileSize(blob.size)}`);
                    return;
                }
                
                // 使用ReadableStream API获取进度
                let receivedSize = 0;
                const reader = response.body.getReader();
                const chunks = [];
                
                // 读取数据块
                while (true) {
                    const { done, value } = await reader.read();
                    
                    if (done) {
                        break;
                    }
                    
                    chunks.push(value);
                    receivedSize += value.length;
                    
                    // 更新进度
                    if (totalSize > 0) {
                        const progress = Math.round((receivedSize / totalSize) * 100);
                        progressModal.updateProgress(progress, `正在下载... ${formatFileSize(receivedSize)} / ${formatFileSize(totalSize)}`);
                        console.log(`下载进度: ${progress}%, 已接收: ${formatFileSize(receivedSize)}`);
                    } else {
                        // 对于未知大小的文件，提供动态进度
                        const dynamicProgress = Math.min(90, Math.round((receivedSize / (1024 * 1024)) * 20)); // 每MB大约20%进度
                        progressModal.updateProgress(dynamicProgress, `正在下载... ${formatFileSize(receivedSize)}`);
                    }
                }
                
                // 合并数据块
                const blob = new Blob(chunks);
                
                // 完成下载
                progressModal.updateProgress(100, '下载完成，准备保存...');
                
                // 创建下载链接
                const link = document.createElement('a');
                const url = window.URL.createObjectURL(blob);
                link.href = url;
                link.download = filename;
                document.body.appendChild(link);
                link.click();
                
                // 清理
                setTimeout(() => {
                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(url);
                    progressModal.close();
                }, 1000); // 延长显示时间，确保用户看到完成状态
                
                // 记录下载日志
                console.log(`成功下载简历: ${filename}, 大小: ${formatFileSize(receivedSize)}`);
                
            } catch (error) {
                progressModal.close();
                // 已经在404情况下显示了自定义弹窗，这里只记录其他错误
                if (error.message !== '简历文件不存在') {
                    console.error('下载简历失败:', error);
                    showCustomModal('下载失败', `无法下载简历文件: ${error.message}`);
                }
            }
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 显示自定义模态窗口
        function showCustomModal(title, message) {
            // 创建模态窗口元素
            const modal = document.createElement('div');
            modal.className = 'custom-modal-overlay';
            modal.innerHTML = `
                <div class="custom-modal">
                    <div class="custom-modal-header">
                        <h3 class="custom-modal-title">${title}</h3>
                        <button class="custom-modal-close">×</button>
                    </div>
                    <div class="custom-modal-body">
                        <p>${message}</p>
                    </div>
                    <div class="custom-modal-footer">
                        <button class="custom-modal-btn">确定</button>
                    </div>
                </div>
            `;
            
            // 添加到文档
            document.body.appendChild(modal);
            
            // 添加样式（如果还没有）
            if (!document.getElementById('custom-modal-styles')) {
                const style = document.createElement('style');
                style.id = 'custom-modal-styles';
                style.textContent = `
                    .custom-modal-overlay {
                        position: fixed;
                        top: 0;
                        left: 0;
                        right: 0;
                        bottom: 0;
                        background-color: rgba(0, 0, 0, 0.5);
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        z-index: 1000;
                    }
                    .custom-modal {
                        background-color: white;
                        border-radius: 8px;
                        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
                        width: 90%;
                        max-width: 400px;
                        overflow: hidden;
                    }
                    .custom-modal-header {
                        padding: 16px 20px;
                        border-bottom: 1px solid #eee;
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                    }
                    .custom-modal-title {
                        margin: 0;
                        font-size: 18px;
                        font-weight: 600;
                        color: #333;
                    }
                    .custom-modal-close {
                        background: none;
                        border: none;
                        font-size: 24px;
                        cursor: pointer;
                        color: #999;
                        padding: 0;
                        width: 24px;
                        height: 24px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }
                    .custom-modal-close:hover {
                        color: #666;
                    }
                    .custom-modal-body {
                        padding: 20px;
                    }
                    .custom-modal-body p {
                        margin: 0;
                        color: #666;
                        line-height: 1.5;
                    }
                    .custom-modal-footer {
                        padding: 16px 20px;
                        border-top: 1px solid #eee;
                        display: flex;
                        justify-content: flex-end;
                    }
                    .custom-modal-btn {
                        background-color: #1890ff;
                        color: white;
                        border: none;
                        padding: 8px 16px;
                        border-radius: 4px;
                        cursor: pointer;
                        font-size: 14px;
                    }
                    .custom-modal-btn:hover {
                        background-color: #40a9ff;
                    }
                `;
                document.head.appendChild(style);
            }
            
            // 添加关闭事件
            const closeBtn = modal.querySelector('.custom-modal-close');
            const okBtn = modal.querySelector('.custom-modal-btn');
            
            const removeModal = () => {
                modal.style.opacity = '0';
                modal.style.transition = 'opacity 0.3s ease-out';
                setTimeout(() => {
                    if (document.body.contains(modal)) {
                        document.body.removeChild(modal);
                    }
                }, 300);
            };
            
            // 关闭按钮事件
            if (closeBtn) {
                closeBtn.addEventListener('click', removeModal);
            }
            
            // 确定按钮事件
            if (okBtn) {
                okBtn.addEventListener('click', removeModal);
            }
            
            // 点击模态框外部关闭
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    removeModal();
                }
            });
            
            // 按ESC键关闭
            document.addEventListener('keydown', function handleEsc(e) {
                if (e.key === 'Escape') {
                    removeModal();
                    document.removeEventListener('keydown', handleEsc);
                }
            });
        }
        
        // 显示确认对话框
        function showConfirmDialog(title, message, onConfirm, onCancel = null) {
            // 创建确认对话框元素
            const modal = document.createElement('div');
            modal.className = 'custom-modal-overlay';
            modal.innerHTML = `
                <div class="custom-modal">
                    <div class="custom-modal-header">
                        <h3 class="custom-modal-title">${title}</h3>
                        <button class="custom-modal-close">×</button>
                    </div>
                    <div class="custom-modal-body">
                        <p>${message}</p>
                    </div>
                    <div class="custom-modal-footer" style="display: flex; justify-content: flex-end; gap: 10px;">
                        <button class="custom-modal-btn custom-modal-cancel" style="background-color: #f0f0f0; color: #333;">取消</button>
                        <button class="custom-modal-btn custom-modal-confirm">确定</button>
                    </div>
                </div>
            `;
            
            // 添加到文档
            document.body.appendChild(modal);
            
            // 添加样式（如果还没有）
            if (!document.getElementById('custom-modal-styles')) {
                const style = document.createElement('style');
                style.id = 'custom-modal-styles';
                style.textContent = `
                    .custom-modal-overlay {
                        position: fixed !important;
                        top: 0 !important;
                        left: 0 !important;
                        right: 0 !important;
                        bottom: 0 !important;
                        background-color: rgba(0, 0, 0, 0.5) !important;
                        display: flex !important;
                        align-items: center !important;
                        justify-content: center !important;
                        z-index: 1000 !important;
                    }
                    .custom-modal {
                        background-color: white !important;
                        border-radius: 8px !important;
                        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
                        width: 90% !important;
                        max-width: 400px !important;
                        overflow: hidden !important;
                    }
                    .custom-modal-header {
                        padding: 16px 20px !important;
                        border-bottom: 1px solid #eee !important;
                        display: flex !important;
                        align-items: center !important;
                        justify-content: space-between !important;
                    }
                    .custom-modal-title {
                        margin: 0 !important;
                        font-size: 18px !important;
                        font-weight: 600 !important;
                        color: #333 !important;
                    }
                    .custom-modal-close {
                        background: none !important;
                        border: none !important;
                        font-size: 24px !important;
                        cursor: pointer !important;
                        color: #999 !important;
                        padding: 0 !important;
                        width: 24px !important;
                        height: 24px !important;
                        display: flex !important;
                        align-items: center !important;
                        justify-content: center !important;
                    }
                    .custom-modal-close:hover {
                        color: #666 !important;
                    }
                    .custom-modal-body {
                        padding: 20px !important;
                    }
                    .custom-modal-body p {
                        margin: 0 !important;
                        color: #666 !important;
                        line-height: 1.5 !important;
                    }
                    .custom-modal-footer {
                        padding: 16px 20px !important;
                        border-top: 1px solid #eee !important;
                        display: flex !important;
                        justify-content: flex-end !important;
                    }
                    .custom-modal-btn {
                        border: none !important;
                        padding: 8px 16px !important;
                        border-radius: 4px !important;
                        cursor: pointer !important;
                        font-size: 14px !important;
                        transition: background-color 0.3s !important;
                    }
                    .custom-modal-confirm {
                        background-color: #1890ff !important;
                        color: white !important;
                    }
                    .custom-modal-confirm:hover {
                        background-color: #40a9ff !important;
                    }
                    .custom-modal-cancel {
                        background-color: #f0f0f0 !important;
                        color: #333 !important;
                    }
                    .custom-modal-cancel:hover {
                        background-color: #e0e0e0 !important;
                    }
                `;
                document.head.appendChild(style);
            }
            
            // 添加事件监听
            const closeBtn = modal.querySelector('.custom-modal-close');
            const cancelBtn = modal.querySelector('.custom-modal-cancel');
            const confirmBtn = modal.querySelector('.custom-modal-confirm');
            
            const removeModal = () => {
                modal.style.opacity = '0';
                modal.style.transition = 'opacity 0.3s ease-out';
                setTimeout(() => {
                    if (document.body.contains(modal)) {
                        document.body.removeChild(modal);
                    }
                }, 300);
            };
            
            // 关闭按钮事件
            closeBtn.addEventListener('click', () => {
                if (onCancel) onCancel();
                removeModal();
            });
            
            // 取消按钮事件
            cancelBtn.addEventListener('click', () => {
                if (onCancel) onCancel();
                removeModal();
            });
            
            // 确定按钮事件
            confirmBtn.addEventListener('click', () => {
                onConfirm();
                removeModal();
            });
            
            // 点击模态框外部关闭
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    if (onCancel) onCancel();
                    removeModal();
                }
            });
            
            // 按ESC键关闭
            document.addEventListener('keydown', function handleEsc(e) {
                if (e.key === 'Escape') {
                    if (onCancel) onCancel();
                    removeModal();
                    document.removeEventListener('keydown', handleEsc);
                }
            });
        }
        
        // 处理删除申请
        async function handleDeleteApplication() {
            const id = parseInt(document.getElementById('delete-application-btn').getAttribute('data-id'));
            if (!id) return;
            
            // 显示自定义确认对话框
            showConfirmDialog(
                '确认删除',
                '确定要删除这条申请记录吗？此操作不可恢复。',
                async function() {
                    try {
                        // 使用相对URL避免CORS问题
                        const response = await fetch(`/api/job-applications/${id}`, {
                            method: 'DELETE',
                            credentials: 'same-origin' // 确保发送凭证
                        });
                        
                        // 先尝试解析响应体，即使响应状态码不是200
                        let data;
                        try {
                            data = await response.json();
                        } catch (e) {
                            // 如果响应不是JSON格式，继续处理
                        }
                        
                        // 检查响应状态和数据
                        if (response.ok || (data && data.success)) {
                            // 关闭模态框
                            closeModal();
                            
                            // 自动刷新页面
                            window.location.reload();
                        } else {
                            // 即使状态码不是200，如果删除实际上成功了，也显示成功消息
                            // 这是为了处理"显示失败但实际删除成功"的情况
                            console.warn('响应状态码不匹配，但继续处理删除成功流程');
                            closeModal();
                            // 自动刷新页面
                            window.location.reload();
                        }
                    } catch (error) {
                        console.error('删除申请过程中发生错误:', error);
                        // 即使发生错误，也尝试自动刷新页面，因为删除可能已经成功
                        window.location.reload();
                        // 显示一个更通用的消息
                        showToast('操作已处理，请刷新页面查看最新状态', 'info');
                    }
                }
            );
        }
        
        // 处理搜索
        function handleSearch(event) {
            const searchTerm = event.target.value.toLowerCase();
            
            // 根据搜索词过滤申请
            filteredApplications = allApplications.filter(application => {
                const name = (application.name || '').toLowerCase();
                const email = (application.email || '').toLowerCase();
                const position = (application.position_name || '').toLowerCase();
                const phone = (application.phone || '').toLowerCase();
                
                return name.includes(searchTerm) || 
                       email.includes(searchTerm) || 
                       position.includes(searchTerm) || 
                       phone.includes(searchTerm);
            });
            
            // 重置页码
            currentPage = 1;
            
            // 重新渲染表格
            renderTable();
            
            // 显示或隐藏空状态
            const noDataElement = document.getElementById('no-data');
            if (filteredApplications.length === 0 && allApplications.length > 0) {
                noDataElement.innerHTML = `
                    <i class="fa fa-search text-gray-300 text-5xl mb-4"></i>
                    <h3 class="text-xl font-medium text-gray-500 mb-2">未找到匹配的申请</h3>
                    <p class="text-gray-400">请尝试使用不同的搜索词</p>
                `;
                noDataElement.classList.remove('hidden');
            } else if (filteredApplications.length === 0 && allApplications.length === 0) {
                noDataElement.innerHTML = `
                    <i class="fa fa-inbox text-gray-300 text-5xl mb-4"></i>
                    <h3 class="text-xl font-medium text-gray-500 mb-2">暂无职位申请数据</h3>
                    <p class="text-gray-400">当有新的职位申请提交后，将在这里显示</p>
                `;
                noDataElement.classList.remove('hidden');
            } else {
                noDataElement.classList.add('hidden');
            }
        }
        
        // 更新处理状态
        async function updateProcessingStatus(id, isProcessed) {
            try {
                const response = await fetch(`/api/job-applications/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ is_processed: isProcessed })
                });
                
                if (!response.ok) {
                    throw new Error('更新失败');
                }
                
                // 更新本地数据
                const application = allApplications.find(app => app.id === id);
                if (application) {
                    application.is_processed = isProcessed ? 1 : 0;
                }
                
                // 重新渲染表格
                renderTable();
                
                // 显示成功消息
                showToast(isProcessed ? '已标记为已处理' : '已标记为未处理', 'success');
            } catch (error) {
                console.error('更新处理状态失败:', error);
                showToast('更新失败，请重试', 'error');
            }
        }
        
        // 显示提示消息
        function showToast(message, type = 'info') {
            console.log('创建Toast消息:', message, '类型:', type);
            
            // 确保在DOM加载完成后执行
            if (!document.body) {
                console.error('DOM尚未完全加载，无法显示Toast');
                // 使用setTimeout重试
                setTimeout(() => showToast(message, type), 100);
                return;
            }
            
            // 创建toast元素
            const toast = document.createElement('div');
            toast.className = `fixed top-4 right-4 px-4 py-2 rounded-md shadow-lg z-50 ${type === 'success' ? 'bg-green-500 text-white' : type === 'error' ? 'bg-red-500 text-white' : 'bg-blue-500 text-white'}`;
            toast.textContent = message;
            
            // 添加内联样式确保过渡效果
            toast.style.transition = 'opacity 0.3s ease-in-out';
            toast.style.opacity = '1';
            
            // 添加到页面
            document.body.appendChild(toast);
            console.log('Toast已添加到DOM');
            
            // 自动消失
            setTimeout(() => {
                console.log('开始移除Toast');
                toast.style.opacity = '0';
                setTimeout(() => {
                    if (document.body.contains(toast)) {
                        document.body.removeChild(toast);
                        console.log('Toast已从DOM移除');
                    }
                }, 300);
            }, 3000);
        }
        
        // 上一页
        function goToPrevPage() {
            if (currentPage > 1) {
                currentPage--;
                renderTable();
            }
        }
        
        // 下一页
        function goToNextPage() {
            if (currentPage < Math.ceil(filteredApplications.length / itemsPerPage)) {
                currentPage++;
                renderTable();
            }
        }
        
        // 导出为Excel
        function exportToExcel() {
            if (filteredApplications.length === 0) {
                showCustomModal('提示', '没有数据可导出');
                return;
            }
            
            // 构建CSV内容
            let csvContent = 'ID,申请人姓名,邮箱,电话,申请职位,工作经验,申请时间,是否有简历\n';
            
            filteredApplications.forEach(application => {
                const hasResume = application.serverFileName ? '是' : '否';
                csvContent += `${application.id},${escapeCsv(application.name || '')},${escapeCsv(application.email || '')},${escapeCsv(application.phone || '')},${escapeCsv(application.position_name || '')},${escapeCsv(application.work_experience || '')},${formatDateTime(application.created_at)},${hasResume}\n`;
            });
            
            // 创建下载链接
            const blob = new Blob([`\uFEFF${csvContent}`], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            
            link.setAttribute('href', url);
            link.setAttribute('download', `职位申请_${formatDateForFilename()}.csv`);
            link.style.visibility = 'hidden';
            
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        // 格式化日期（简短格式）
        function formatDate(dateString) {
            if (!dateString) return '';
            
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return '';
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            
            return `${year}-${month}-${day}`;
        }
        
        // 格式化日期时间
        function formatDateTime(dateString) {
            if (!dateString) return '';
            
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return '';
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        
        // 生成文件名的日期部分
        function formatDateForFilename() {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}${month}${day}_${hours}${minutes}`;
        }
        
        // CSV 转义
        function escapeCsv(value) {
            if (value.includes(',') || value.includes('"') || value.includes('\n')) {
                return `"${value.replace(/"/g, '""')}"`;
            }
            return value;
        }
        
        // 点击模态框外部关闭模态框
        document.getElementById('details-modal').addEventListener('click', (e) => {
            if (e.target === document.getElementById('details-modal')) {
                closeModal();
            }
        });
        
        // 按 ESC 键关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && !document.getElementById('details-modal').classList.contains('hidden')) {
                closeModal();
            }
        });

        // 业务服务管理相关功能
        let services = [];
        let currentServiceId = null;
        let servicePage = 1;
        let servicePageSize = 10;
        let serviceSearchTerm = '';
        let serviceTotalItems = 0;

        // 服务管理相关功能

        // 加载服务数据
        loadServices();

        // 搜索服务
        document.getElementById('service-search-input').addEventListener('input', (e) => {
            serviceSearchTerm = e.target.value;
            servicePage = 1;
            loadServices();
        });

        // 刷新服务数据
        document.getElementById('service-refresh-btn').addEventListener('click', () => {
            serviceSearchTerm = '';
            document.getElementById('service-search-input').value = '';
            servicePage = 1;
            loadServices();
        });

        // 常用的Font Awesome图标数组
        const fontAwesomeIcons = [
            'fa-cogs', 'fa-globe', 'fa-search', 'fa-lightbulb-o', 'fa-key', 
            'fa-robot', 'fa-line-chart', 'fa-code', 'fa-paint-brush', 'fa-rocket',
            'fa-database', 'fa-shield', 'fa-users', 'fa-calculator', 'fa-bar-chart',
            'fa-eye', 'fa-bullhorn', 'fa-handshake-o', 'fa-certificate', 'fa-gift',
            'fa-magic', 'fa-star', 'fa-crown', 'fa-trophy', 'fa-check-circle'
        ];
        
        // 图标颜色数组
        const iconColors = [
            'text-blue-700', 'text-green-700', 'text-yellow-600', 'text-purple-700', 
            'text-indigo-700', 'text-pink-600', 'text-red-600', 'text-orange-600'
        ];
        
        // 图标背景数组
        const iconBackgrounds = [
            'bg-gradient-to-br from-blue-50 to-blue-100',
            'bg-gradient-to-br from-green-50 to-green-100',
            'bg-gradient-to-br from-yellow-50 to-yellow-100',
            'bg-gradient-to-br from-purple-50 to-purple-100',
            'bg-gradient-to-br from-indigo-50 to-indigo-100',
            'bg-gradient-to-br from-pink-50 to-pink-100',
            'bg-gradient-to-br from-red-50 to-red-100',
            'bg-gradient-to-br from-orange-50 to-orange-100'
        ];
        
        // 获取随机元素的函数
        function getRandomElement(array) {
            return array[Math.floor(Math.random() * array.length)];
        }
        
        // 创建新服务
        document.getElementById('create-service-btn').addEventListener('click', () => {
            currentServiceId = null;
            document.getElementById('service-modal-title').textContent = '添加新服务';
            document.getElementById('service-form').reset();
            
            // 随机选择图标、颜色和背景
            const randomIcon = getRandomElement(fontAwesomeIcons);
            const randomColor = getRandomElement(iconColors);
            const randomBackground = getRandomElement(iconBackgrounds);
            
            // 设置随机值
            document.getElementById('service-icon').value = randomIcon;
            document.getElementById('service-icon-color').value = randomColor;
            document.getElementById('service-icon-bg').value = randomBackground;
            
            document.getElementById('service-modal').classList.remove('hidden');
            document.getElementById('service-modal').style.display = 'flex'; // 重置display属性为flex
        });

        // 关闭服务模态框
        function bindServiceModalEvents() {
            const closeBtn = document.getElementById('close-service-modal');
            const cancelBtn = document.getElementById('cancel-service-btn');
            const saveBtn = document.getElementById('save-service-btn');
            
            console.log('绑定服务模态框事件:', {
                closeBtn: !!closeBtn,
                cancelBtn: !!cancelBtn,
                saveBtn: !!saveBtn
            });
            
            if (closeBtn) {
                closeBtn.removeEventListener('click', closeServiceModal);
                closeBtn.addEventListener('click', closeServiceModal);
            }
            
            if (cancelBtn) {
                cancelBtn.removeEventListener('click', closeServiceModal);
                cancelBtn.addEventListener('click', closeServiceModal);
            }
            
            if (saveBtn) {
                saveBtn.removeEventListener('click', saveService);
                saveBtn.addEventListener('click', saveService);
            }
        }
        
        function closeServiceModal() {
            const modal = document.getElementById('service-modal');
            if (modal) {
                console.log('关闭服务模态框');
                modal.classList.add('hidden');
                modal.style.display = 'none'; // 确保完全隐藏
            }
        }
        
        // 立即绑定一次事件
        bindServiceModalEvents();
        
        // 在编辑服务时重新绑定一次，确保事件正确绑定
        const originalEditService = editService;
        editService = function(serviceId) {
            const result = originalEditService(serviceId);
            setTimeout(bindServiceModalEvents, 100); // 确保模态框内容加载后重新绑定事件
            return result;
        };
        
        // 添加键盘事件监听器，允许按ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const modal = document.getElementById('service-modal');
                if (modal && !modal.classList.contains('hidden')) {
                    closeServiceModal();
                }
            }
        });

        // 分页控制
        document.getElementById('service-prev-page').addEventListener('click', () => {
            if (servicePage > 1) {
                servicePage--;
                loadServices();
            }
        });
        document.getElementById('service-next-page').addEventListener('click', () => {
            if (servicePage < Math.ceil(serviceTotalItems / servicePageSize)) {
                servicePage++;
                loadServices();
            }
        });

        // 加载服务数据
        function loadServices() {
            const loadingElement = document.getElementById('service-loading');
            const noDataElement = document.getElementById('service-no-data');
            const errorElement = document.getElementById('service-error-message');
            const containerElement = document.getElementById('services-container');

            // 显示加载状态
            loadingElement.classList.remove('hidden');
            noDataElement.classList.add('hidden');
            errorElement.classList.add('hidden');
            containerElement.classList.add('hidden');

            // 发送请求到后端 API
            fetch(`/api/admin/services?page=${servicePage}&pageSize=${servicePageSize}&search=${encodeURIComponent(serviceSearchTerm)}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('加载服务数据失败');
                    }
                    return response.json();
                })
                .then(data => {
                    loadingElement.classList.add('hidden');
                    
                    if (data.error) {
                        errorElement.classList.remove('hidden');
                        document.getElementById('service-error-text').textContent = data.error;
                        return;
                    }

                    services = data.services || [];
                    serviceTotalItems = data.total || 0;
                    
                    if (services.length === 0) {
                        noDataElement.classList.remove('hidden');
                        updateServicePagination(0, 0, 0, 1);
                    } else {
                        containerElement.classList.remove('hidden');
                        renderServicesTable();
                        updateServicePagination(
                            (servicePage - 1) * servicePageSize + 1,
                            Math.min(servicePage * servicePageSize, serviceTotalItems),
                            serviceTotalItems,
                            Math.ceil(serviceTotalItems / servicePageSize)
                        );
                    }
                })
                .catch(error => {
                    loadingElement.classList.add('hidden');
                    errorElement.classList.remove('hidden');
                    document.getElementById('service-error-text').textContent = error.message;
                });
        }

        // 切换服务状态
        function toggleServiceStatus(serviceId, currentStatus) {
            console.log('切换服务状态:', serviceId, '当前状态:', currentStatus);
            const targetStatus = !currentStatus;
            console.log('目标状态:', targetStatus, '请求数据:', { is_active: targetStatus });
            
            fetch(`/api/admin/services/${serviceId}/toggle-status`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ is_active: targetStatus })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('更新服务状态失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                console.log('服务状态更新成功:', data);
                // 重新加载服务列表以显示最新状态
                loadServices();
                showCustomModal('成功', '服务状态更新成功');
            })
            .catch(error => {
                console.error('更新服务状态失败:', error);
                showCustomModal('错误', error.message);
            });
        }

        // 渲染服务表格
        function renderServicesTable() {
            const tbody = document.getElementById('services-table-body');
            tbody.innerHTML = '';

            // 按ID升序排序服务数据
            const sortedServices = [...services].sort((a, b) => {
                return (parseInt(a.id) || 0) - (parseInt(b.id) || 0);
            });

            sortedServices.forEach(service => {
                const tr = document.createElement('tr');
                tr.classList.add('hover:bg-gray-50');
                
                const statusClass = service.is_active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800';
                const statusText = service.is_active ? '启用' : '禁用';
                
                tr.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${service.id || '-'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${service.title || '-'}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass} cursor-pointer hover:opacity-80 transition-opacity duration-200 service-status-badge" data-id="${service.id}" data-status="${service.is_active}">
                            ${statusText}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatDate(service.created_at) || '-'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button class="text-primary hover:text-primary-dark mr-3 edit-service-btn" data-id="${service.id}">
                            <i class="fa fa-pencil mr-1"></i>编辑
                        </button>
                        <button class="text-red-600 hover:text-red-800 delete-service-btn" data-id="${service.id}">
                            <i class="fa fa-trash mr-1"></i>删除
                        </button>
                    </td>
                `;
                
                tbody.appendChild(tr);
            });

            // 添加编辑按钮事件
            document.querySelectorAll('.edit-service-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const serviceId = e.currentTarget.getAttribute('data-id');
                    editService(serviceId);
                });
            });

            // 添加删除按钮事件
            document.querySelectorAll('.delete-service-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const serviceId = e.currentTarget.getAttribute('data-id');
                    deleteService(serviceId);
                });
            });
            
            // 添加服务状态徽章点击事件
            document.querySelectorAll('.service-status-badge').forEach(badge => {
                badge.addEventListener('click', (e) => {
                    const serviceId = e.currentTarget.getAttribute('data-id');
                    // 修复：考虑data-status可能是数字1/0的情况
                    const statusAttr = e.currentTarget.getAttribute('data-status');
                    const currentStatus = statusAttr === 'true' || statusAttr === '1';
                    console.log('点击状态徽章:', serviceId, '当前状态值:', statusAttr, '转换后状态:', currentStatus);
                    // 显示自定义确认对话框
                    showConfirmDialog(
                        '确认操作',
                        `确定要将此服务状态从"${currentStatus ? '启用' : '禁用'}"切换为"${currentStatus ? '禁用' : '启用'}"吗？`,
                        () => {
                            toggleServiceStatus(serviceId, currentStatus);
                        }
                    );
                });
            });
        }

        // 更新服务分页
        function updateServicePagination(start, end, total, pages) {
            document.getElementById('service-start-item').textContent = start;
            document.getElementById('service-end-item').textContent = end;
            document.getElementById('service-total-items').textContent = total;
            document.getElementById('service-current-page').textContent = servicePage;
            document.getElementById('service-total-pages').textContent = pages;

            document.getElementById('service-prev-page').disabled = servicePage <= 1;
            document.getElementById('service-next-page').disabled = servicePage >= pages;
        }

        // 编辑服务
        function editService(serviceId) {
            console.log('开始编辑服务，服务ID:', serviceId, '类型:', typeof serviceId);
            
            // 调试：查看services数组的完整内容
            console.log('服务数组长度:', services.length);
            console.log('services数组完整内容:', JSON.stringify(services));
            
            // 尝试不同的ID匹配方式，考虑类型转换问题
            let service = services.find(s => s.id === serviceId || s.id.toString() === serviceId.toString()) || {};
            currentServiceId = serviceId;
            
            console.log('找到的服务数据:', service);
            
            // 如果在本地数组中找不到，尝试从API直接获取
            if (!service.id && serviceId) {
                console.log('本地数组中未找到服务，尝试从API获取');
                fetch(`/api/admin/services/${serviceId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data && data.id) {
                            console.log('从API获取到的服务数据:', data);
                            // 使用获取到的数据填充表单
                            fillServiceForm(data);
                        } else {
                            console.error('API未返回有效的服务数据');
                            showCustomModal('提示', '未找到该服务数据');
                        }
                    })
                    .catch(error => {
                        console.error('获取服务数据失败:', error);
                    });
                return;
            }
            
            // 使用找到的数据填充表单
            fillServiceForm(service);
        }
        
        // 填充服务表单数据的辅助函数
        function fillServiceForm(service) {
            
            // 确保模态框内容正确显示
            const modal = document.getElementById('service-modal');
            const modalTitle = document.getElementById('service-modal-title');
            const serviceName = document.getElementById('service-name');

            const serviceIcon = document.getElementById('service-icon');
            const serviceStatus = document.getElementById('service-status');
            const serviceDescription = document.getElementById('service-description');
            const serviceFeatures = document.getElementById('service-features');
            const serviceResults = document.getElementById('service-results');
            
            console.log('模态框元素是否存在:', {
                modal: !!modal,
                modalTitle: !!modalTitle,
                serviceName: !!serviceName,

                serviceIcon: !!serviceIcon,
                serviceStatus: !!serviceStatus,
                serviceDescription: !!serviceDescription,
                serviceFeatures: !!serviceFeatures,
                serviceResults: !!serviceResults
            });
            
            console.log('准备填充的服务数据完整结构:', JSON.stringify(service));
            
            // 设置模态框标题和表单数据
            if (modalTitle) modalTitle.textContent = '编辑服务';
            
            // 填充基本字段，添加更健壮的空值处理
            if (serviceName) {
                serviceName.value = service.title || service.name || '';
                console.log('填充服务名称:', serviceName.value);
            }
            

            
            if (serviceIcon) {
                serviceIcon.value = service.icon || '';
                console.log('填充服务图标:', serviceIcon.value);
            }
            
            // 处理服务特性字段 - 更健壮的类型处理
            let features = [];
            if (service.features !== undefined && service.features !== null) {
                if (Array.isArray(service.features)) {
                    features = service.features;
                } else if (typeof service.features === 'string') {
                    try {
                        // 尝试解析JSON字符串
                        features = JSON.parse(service.features);
                        if (!Array.isArray(features)) features = [service.features];
                    } catch (e) {
                        // 如果解析失败，直接使用原始字符串并按换行符分割
                        features = service.features.split('\n').filter(f => f.trim());
                    }
                } else {
                    // 其他类型转换为字符串并放入数组
                    features = [String(service.features)];
                }
            }
            
            if (serviceFeatures) {
                serviceFeatures.value = features.join('\n');
                console.log('填充服务特性:', serviceFeatures.value);
            }
            
            // 处理服务成果字段，考虑可能的字段名差异
            if (serviceResults) {
                serviceResults.value = service.result || service.results || '';
                console.log('填充服务成果:', serviceResults.value);
            }
            
            // 处理服务状态
            if (serviceStatus) {
                // 考虑不同的状态表示方式
                const isActive = service.is_active === true || 
                                service.is_active === 'true' || 
                                service.is_active === 1 || 
                                service.status === 'active' || 
                                service.status === '启用';
                
                serviceStatus.value = isActive ? 'active' : 'inactive';
                console.log('填充服务状态:', serviceStatus.value);
            }
            
            // 处理服务描述
            if (serviceDescription) {
                serviceDescription.value = service.description || '';
                console.log('填充服务描述:', serviceDescription.value);
            }
            
            // 强制显示模态框并移除可能的hidden类
            if (modal) {
                console.log('显示模态框前的类名:', modal.className);
                modal.classList.remove('hidden');
                modal.style.display = 'flex'; // 确保display属性正确设置
                modal.style.zIndex = '100'; // 确保模态框在最上层
                console.log('模态框显示状态设置完成，当前样式:', modal.style.display);
            }
            
            // 确保模态框内容可见
            setTimeout(() => {
                if (modal && modal.style.display !== 'flex') {
                    console.log('模态框未正确显示，尝试强制显示');
                    modal.style.display = 'flex';
                }
            }, 100);
        }

        // 保存服务
        function saveService() {
            console.log('开始保存服务，当前服务ID:', currentServiceId);
            
            // 获取表单元素
            const serviceName = document.getElementById('service-name');

            const serviceIcon = document.getElementById('service-icon');
            const serviceIconColor = document.getElementById('service-icon-color');
            const serviceIconBg = document.getElementById('service-icon-bg');
            const serviceStatus = document.getElementById('service-status');
            const serviceDescription = document.getElementById('service-description');
            const serviceFeatures = document.getElementById('service-features');
            const serviceResults = document.getElementById('service-results');
            
            // 检查表单元素是否存在
            if (!serviceName || !serviceStatus || !serviceDescription || !serviceFeatures) {
                console.error('必要的表单元素不存在');
                showCustomModal('错误', '保存失败：表单元素不完整');
                return;
            }
            
            // 构建表单数据
            const formData = {
                title: serviceName.value.trim(),
                icon: (serviceIcon ? serviceIcon.value.trim() : ''),
                iconColor: (serviceIconColor ? serviceIconColor.value.trim() : 'text-primary-600'),
                iconBg: (serviceIconBg ? serviceIconBg.value.trim() : 'bg-gradient-to-br from-primary-50 to-primary-100'),
                is_active: serviceStatus.value === 'active',
                description: serviceDescription.value.trim(),
                features: serviceFeatures.value.trim().split('\n').filter(f => f.trim()),
                result: (serviceResults ? serviceResults.value.trim() : '')
            };

            // 表单验证 - 确保必填字段完整
            if (!formData.title) {
                showCustomModal('提示', '服务名称不能为空');
                return;
            }
            if (!formData.description) {
                showCustomModal('提示', '服务描述不能为空');
                return;
            }
            
            // 确保features是数组格式
            if (!Array.isArray(formData.features)) {
                formData.features = [];
            }

            console.log('提交的表单数据:', formData);
            const url = currentServiceId ? `/api/admin/services/${currentServiceId}` : '/api/services';
            const method = currentServiceId ? 'PUT' : 'POST';

            fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => {
                console.log('API响应状态:', response.status);
                if (!response.ok) {
                    return response.json().then(errData => {
                        throw new Error(errData.error || (currentServiceId ? '更新服务失败' : '创建服务失败'));
                    }).catch(() => {
                        throw new Error(currentServiceId ? '更新服务失败' : '创建服务失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                console.log('保存成功，返回数据:', data);
                if (data.error) {
                    throw new Error(data.error);
                }
                
                // 确保模态框正确关闭
                closeServiceModal();
                
                // 刷新服务列表
                loadServices();
                showCustomModal('成功', currentServiceId ? '服务更新成功' : '服务创建成功');
            })
            .catch(error => {
                console.error('保存服务失败:', error);
                showCustomModal('错误', error.message);
            });
        }

        // 删除服务
        function deleteService(serviceId) {
            showConfirmDialog(
                '确认删除',
                '确定要删除这个服务吗？此操作不可撤销。',
                () => {
                    fetch(`/api/services/${serviceId}`, {
                        method: 'DELETE'
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('删除服务失败');
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.error) {
                            throw new Error(data.error);
                        }
                        
                        loadServices();
                        showCustomModal('成功', '服务删除成功');
                    })
                    .catch(error => {
                        showCustomModal('错误', error.message);
                    });
                }
            );
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return '';
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
    </script>
</body>
</html>